﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Resources;
using System.Globalization;
namespace Microsoft.MCSUK.SPSiteDirectory2010.SiteDataWebpart
{
    [ToolboxItemAttribute(false)]
    public class SiteDataWebpart : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/Microsoft.MCSUK.SPSiteDirectory2010/SiteDataWebpart/SiteDataWebpartUserControl.ascx";

        public const Boolean showTitleDefault = true;
        private Boolean showTitle = showTitleDefault;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [LocalizedCatgeory("SiteDataWebpart_WebpartProperties_Category")]
        [LocalizedWebDisplayName("SiteDataWebpart_WebpartProperties_ShowTitle_DisplayName")]
        [LocalizedWebDescription("SiteDataWebpart_WebpartProperties_ShowTitle_Description")]
        [DefaultValue(showTitleDefault)]
        public Boolean ShowTitle
        {
            get { return showTitle; }
            set { showTitle = value; }
        }

        public const Boolean displaySiteImageDefault = true;
        private Boolean displaySiteImage = displaySiteImageDefault;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [LocalizedCatgeory("SiteDataWebpart_WebpartProperties_Category")]
        [LocalizedWebDisplayName("SiteDataWebpart_WebpartProperties_ShowImage_DisplayName")]
        [LocalizedWebDescription("SiteDataWebpart_WebpartProperties_ShowImage_Description")]
        [DefaultValue(displaySiteImageDefault)]
        public Boolean DisplaySiteImage
        {
            get { return displaySiteImage; }
            set { displaySiteImage = value; }
        }

        public const string excludedFieldsDefault = "SiteMissingCount,SiteTemplate,SiteID,SiteURL,SiteSubWebs,SiteMultiLingual,SiteAuthor,SiteSecondaryContact,SiteStorage,SiteHits,SiteQuotaUsed,SiteImage,ParentSiteID,SiteLanguage";
        private string excludedFields = excludedFieldsDefault;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [LocalizedCatgeory("SiteDataWebpart_WebpartProperties_Category")]
        [LocalizedWebDisplayName("SiteDataWebpart_WebpartProperties_FieldsToExclude_DisplayName")]
        [LocalizedWebDescription("SiteDataWebpart_WebpartProperties_FieldsToExclude_Description")]
        [DefaultValue(excludedFieldsDefault)]
        public string ExcludedFields
        {
            get { return excludedFields; }
            set { excludedFields = value; }
        }

        public const string CSSDefault = "/_layouts/SPSiteDirectory2010/SiteDataWebpart.css";
        private string css = CSSDefault;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [LocalizedCatgeory("SiteDataWebpart_WebpartProperties_Category")]
        [LocalizedWebDisplayName("SiteDataWebpart_WebpartProperties_CSS_DisplayName")]
        [LocalizedWebDescription("SiteDataWebpart_WebpartProperties_CSS_Description")] //refer to http://msdn.microsoft.com/en-us/library/ms426441.aspx.
        [DefaultValue(CSSDefault)]
        public string CSS
        {
            get { return css; }
            set { css = value; }
        }

        public class LocalizedCatgeory : WebDescriptionAttribute
        {
            public LocalizedCatgeory(string resId)
            {
                base.DescriptionValue = FetchLocalizedString(resId);
            }
            string FetchLocalizedString(string resourceID)
            {
                ResourceManager rm = SiteDataWebpartResources.ResourceManager;
                return rm.GetString(resourceID);
            }
        }

        public class LocalizedWebDisplayName : WebDisplayNameAttribute
        {
            public LocalizedWebDisplayName(string resId)
            {
                base.DisplayNameValue = FetchLocalizedString(resId);
            }
            string FetchLocalizedString(string resourceID)
            {
                ResourceManager rm = SiteDataWebpartResources.ResourceManager;
                return rm.GetString(resourceID);
            }
        }

        public class LocalizedWebDescription : WebDescriptionAttribute
        {
            public LocalizedWebDescription(string resId)
            {
                base.DescriptionValue = FetchLocalizedString(resId);
            }
            string FetchLocalizedString(string resourceID)
            {
                ResourceManager rm = SiteDataWebpartResources.ResourceManager;
                return rm.GetString(resourceID);
            }
        }

        protected override void CreateChildControls()
        {                
            //register ASCXs
            SiteDataWebpartUserControl userControl = (SiteDataWebpartUserControl)this.Page.LoadControl(_ascxPath);

            //Get controls from ASCX
            Table tblFields = (Table)userControl.FindControl("tblFields");
            Label lblError = (Label)userControl.FindControl("lblError");
            HyperLink lnkSeeFullDetails = (HyperLink)userControl.FindControl("lnkSeeFullDetails");
            Image imgSiteImage = (Image)userControl.FindControl("imgSiteImage");

            //Load controls with data
            GlobalMethods globalMethods = new GlobalMethods();
            try
            {
                //set the CSS if one is configured
                if (!String.IsNullOrEmpty(css))
                {
                    CssRegistration.Register(css);
                }

                //populate controls
                GlobalSolutionSettings globalSettings = globalMethods.GetOrCreateGlobalSolutionSettings(SPFarm.Local);
                if (globalMethods.DoesSiteExist(globalSettings.SiteDirectoryURL))
                {
                    using (SPSite thisSite = SPContext.Current.Site)
                    {
                        using (SPWeb thisWeb = SPContext.Current.Web)
                        {
                            SPListItem siteListing = globalMethods.GetSiteListing(thisWeb.ID);
                            if (siteListing != null)
                            {
                                //display the title if not excluded
                                if (!excludedFields.Contains("Title"))
                                {
                                    tblFields.Rows.Add(ConstructTableRow(thisSite, thisWeb, siteListing, siteListing.Fields["Title"], globalMethods));
                                }
                                //display the details of each field that is not excluded
                                foreach (SPField f in siteListing.Fields)
                                {
                                    if ((f.Group == GlobalConstants.SolutionName) && (!ExcludedFields.Contains(f.StaticName)))
                                    {
                                        tblFields.Rows.Add(ConstructTableRow(thisSite, thisWeb, siteListing, f, globalMethods));
                                    }
                                }
                            }

                            //display site image
                            if ((displaySiteImage) && (siteListing["SiteImage"] != null))
                            {
                                imgSiteImage.Style.Add("display", "Inline");
                                SPFieldUrlValue siteImage = new SPFieldUrlValue(siteListing["SiteImage"].ToString());
                                imgSiteImage.ImageUrl = siteImage.Url;
                                imgSiteImage.AlternateText = "Image that represents the site";
                            }
                            else
                            {
                                imgSiteImage.Style.Add("display", "None");
                            }

                            //update more details link
                            using (SPSite siteDirectorySite = new SPSite(globalSettings.SiteDirectorySiteGuid))
                            {
                                using (SPWeb siteDirectoryWeb = siteDirectorySite.OpenWeb(globalSettings.SiteDirectoryWebGuid))
                                {
                                    lnkSeeFullDetails.NavigateUrl = globalMethods.GetSiteListingsListURL(siteDirectoryWeb) + GlobalConstants.SiteListingDisplayFormWithParameter + siteListing.ID;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //adjust visibility
                lblError.Style.Add("Display", "Inline");
                imgSiteImage.Style.Add("Display", "None");
                tblFields.Style.Add("Display", "None");
                lnkSeeFullDetails.Style.Add("Display", "None");

                //lblError.Text = HttpContext.GetGlobalResourceObject("SPSiteDirectory2010GlobalResources", "Code_GenericUIErrorText").ToString();
                lblError.Text = ex.ToString();
                globalMethods.WriteULSEntry(ex, TraceSeverity.Unexpected, null);
            }

            //add controls
            Controls.Add(userControl);
        }

        private TableRow ConstructTableRow(SPSite thisSite, SPWeb thisWeb, SPListItem siteListing, SPField f, GlobalMethods globalMethods)
        {
            TableRow tr = new TableRow();

            //add title if property is true
            if (ShowTitle)
            {
                TableCell tdTitle = new TableCell();
                tdTitle.VerticalAlign = VerticalAlign.Top;
                //tdTitle.Text = f.Title;
                tdTitle.Text = f.TitleResource.GetValueForUICulture(CultureInfo.CurrentUICulture);
                tr.Cells.Add(tdTitle);
            }

            //add value to cell. using differnet controls depending on what the field type is
            TableCell tdValue = new TableCell();
            tdValue.VerticalAlign = VerticalAlign.Top;
            if (siteListing[f.Id] != null)
            {
                switch (f.Type)
                {
                    case SPFieldType.DateTime:
                        tdValue.Text = Convert.ToDateTime(siteListing[f.Id]).ToShortDateString();
                        break;
                    case SPFieldType.User:
                        SPFieldUserValueCollection uvc = new SPFieldUserValueCollection(thisWeb, siteListing[f.Id].ToString());
                        tdValue.Text = globalMethods.GetPresenceHTMLFromUVC(thisSite, uvc);
                        break;
                    case SPFieldType.URL:
                        if (f.StaticName != "SiteImage")
                        {
                            SPFieldUrlValue furl = new SPFieldUrlValue(siteListing[f.Id].ToString());
                            HyperLink hl = new HyperLink();
                            hl.NavigateUrl = furl.Url;
                            hl.Text = furl.Description;
                            tdValue.Controls.Add(hl);
                        }
                        break;
                    default:
                        tdValue.Text = siteListing[f.Id].ToString();
                        break;
                }
            }
            else
            {
                tdValue.Text = "";
            }

            //add cells to row
            tr.Cells.Add(tdValue);
            return tr;
        }
    }
}
